package com.biz.primus.ms.price.dao.specification;

import com.biz.primus.model.price.vo.PriceQueryVo;
import com.biz.primus.ms.price.dao.po.Price;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.jpa.domain.Specification;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.List;

public class PriceSpecification implements Specification<Price> {

    private PriceQueryVo reqVo;

    public PriceSpecification(PriceQueryVo priceQueryVo) {
        this.reqVo = priceQueryVo;
    }

    @Override
    public Predicate toPredicate(Root<Price> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
        List<Predicate> predicates = Lists.newArrayList();
        criteriaQuery.orderBy(criteriaBuilder.desc(root.get("createTimestamp")));
        if (StringUtils.isNotBlank(reqVo.getProductCode())) {
            Predicate predicate = criteriaBuilder.equal(root.get("productCode").as(String.class), reqVo.getProductCode());
            predicates.add(predicate);

        }
        if (StringUtils.isNotBlank(reqVo.getDepotCode())) {
            Predicate predicate = criteriaBuilder.like(root.get("depotCode").as(String.class), reqVo.getDepotCode());
            predicates.add(predicate);
        }
        if(StringUtils.isNotBlank(reqVo.getPriceType())){
            if (reqVo.getMinPrice() != null){
                Predicate predicate = criteriaBuilder.ge(root.get(reqVo.getPriceType()).as(Integer.class), reqVo.getMinPrice());
                predicates.add(predicate);
            }
            if (reqVo.getMaxPrice() != null){
                Predicate predicate = criteriaBuilder.le(root.get(reqVo.getPriceType()).as(Integer.class), reqVo.getMaxPrice());
                predicates.add(predicate);
            }
        }
        criteriaQuery.where(predicates.toArray(new Predicate[predicates.size()]));
        return criteriaQuery.getRestriction();
    }

}
